package com.qzsf.backend.interceptors;
/*
 * @Author: Dennis Chen
 * @CreateTime: 2024/10/10 9:25 周四
 * @Email 1429278462@qq.com
 * @Remark 登录拦截器对象
 * @Version 1.0
 */

import com.qzsf.backend.util.JwtUtil;
import com.qzsf.backend.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        try {
            //从redis中获取相同的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);

            if(redisToken == null){
                //token已经失效
                throw new RuntimeException();
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(claims);

            String role = (String) claims.get("role");
            //当前角色
            System.out.println("role="+role);
            String requestURI = request.getRequestURI();
            if ((requestURI.startsWith("/admins")&&!role.equals("ADMIN"))){
                response.setCharacterEncoding("UTF-8");  // 设置字符编码
                response.setContentType("application/json;charset=UTF-8"); // 设置响应内容类型
                response.getWriter().write("{\"message\":\"当前用户权限不足\"}");  // 输出中文报错信息
                return false;
            }
            //通过
            return true;
        } catch (Exception e) {
            //响应状态码401
            response.setStatus(401);
            //未通过
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal数据
        ThreadLocalUtil.remove();
    }
}

